/*
 * DefaultContentMatrix.java
 * 
 * Created on Jun 12, 2007, 7:21:25 PM
 * 
 * Copyright (c) 2007 Daniel Gronau
 *
 * This file is part of KanjiTori.
 *
 * KanjiTori is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * KanjiTori is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */

package kanjitori.map;

import java.util.Arrays;
import java.util.Random;

import static kanjitori.map.Position.Direction;

/**
 *
 * @author DGronau
 */
class DefaultContentMatrix implements ContentMatrix {

    private static final Random RANDOM = new Random();

    private Position size;
    private Content[][] contents;
    
    public DefaultContentMatrix(Position size) {
        this.size = size;
        contents = new Content[size.x()][size.y()];
        for (int x = 0; x < size.x(); x++) {
            Arrays.fill(contents[x], Content.EMPTY);
        }
    }
    
    /**
     * 
     * @return 
     */
    public Position findFreePos() {
        outer:
        while(true) {
            Position pos = Position.get(RANDOM.nextInt(size.x()), RANDOM.nextInt(size.y()));
            if (getContent(pos) == Content.EMPTY) {
                for (Direction direction : Direction.values()) {
                    Position p = pos.getNeighbor(direction);
                    if (isValidPos(p) && getContent(p) == Content.BOT) {
                        continue outer;
                    }
                }
                return pos;
            }
        }
    }    

    public Content getContent(Position p) {
        return isValidPos(p) ? contents[p.x()][p.y()] : Content.SOLID;
    }

    public void setContent(Position p, Content content) {
        contents[p.x()][p.y()] = content;
    }

     public boolean isValidPos(Position p) {
        return 0 <= p.x() && p.x() < size.x() && 0 <= p.y() && p.y() < size.y();
    }

    public Position getSize() {
        return size;
    }

}
